package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {

        // 只解决缓存穿透
        // Shop shop = queryWithPassThrough(id);

        // 使用互斥锁解决缓存击穿，缓存空值解决缓存穿透
        // Shop shop = queryWithMutex(id);

        // 使用逻辑过期解决缓存击穿，缓存空值解决缓存穿透
        // Shop shop = queryByIdWithLogicalExpire(id);
        // if (null == shop) {
        //     return Result.fail("店铺不存在！");
        // }

        // 只解决缓存穿透
        Shop shop = cacheClient.queryWithMutex(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
                (idx)->{
                    return getById(idx);
                },
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);


        return Result.ok(shop);
    }


    public Shop queryByIdWithLogicalExpire(Long id){
        // 1. 从Redis查询商铺缓存
        String redisDataJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        // 2. 判断缓存中是否存在
        if (StrUtil.isNotBlank(redisDataJson)) {
            // 3. 存在，且未过期，直接返回
            RedisData redisData = JSONUtil.toBean(redisDataJson, RedisData.class);
            Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
                return shop;
            } else{
                // 4. 过期，则缓存重建
                String lock = RedisConstants.LOCK_SHOP_KEY + id;
                try {
                    if(tryLock(lock)){
                        // 5. 获取锁成功，二次检查缓存
                        String secondRedisDataJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
                        if(StrUtil.isNotBlank(secondRedisDataJson)){
                            RedisData secondRedisData = JSONUtil.toBean(secondRedisDataJson, RedisData.class);
                            if(secondRedisData.getExpireTime().isAfter(LocalDateTime.now())){
                                JSONObject secondShopJson = (JSONObject) secondRedisData.getData();
                                return JSONUtil.toBean(secondShopJson, Shop.class);
                            }
                        }

                        // 6. 缓存中不存在，根据id查询数据库
                        shop = getById(id);
                        if (null == shop) {
                            // 6. 不存在，返回错误，将空值写入Redis
                            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",
                                    RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                            return null;
                        }
                        // 7. 使用线程池中执行，避免阻塞线程
                        Shop finalShop = shop;
                        CACHE_REBUILD_EXECUTOR.submit(() -> {
                            this.saveShop2Redis(finalShop, RedisConstants.CACHE_SHOP_TTL);
                        });

                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lock);
                }

                // 7. 返回，若缓存重建成功，则返回新值，否则返回旧值
                return shop;
            }
        }

        // 4. 判断命中的是否是空值
        if("".equals(redisDataJson)){
            return null;
        }

        // 4. 缓存中不存在，根据id查询数据库
        Shop shop = getById(id);

        // 5. 数据库中不存在，返回错误，将空值写入Redis
        if (null == shop) {
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",
                    RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        } else{
            // 6. 数据库中存在，将shop写入Redis
            saveShop2Redis(shop, RedisConstants.CACHE_SHOP_TTL);
        }

        return shop;
    }


    public void saveShop2Redis(Shop shop, Long expireSeconds){

        RedisData redisData = new RedisData();
        redisData.setData(shop);
        // 设置逻辑过期时间
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + shop.getId(),
                JSONUtil.toJsonStr(redisData));
    }



    /**
     * 解决缓存击穿和穿透
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id){
        // 1. 从Redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        // 2. 判断缓存中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3. 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        // 4. 判断命中的是否是空值
        if("".equals(shopJson)){
            return null;
        }

        // 4. 不存在，重建缓存
        // 4.1 获取锁
        Shop shop;
        String lock = RedisConstants.LOCK_SHOP_KEY + id;
        try {
            if(!tryLock(lock)){
                // 5. 获取锁失败，等待并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 4.2 再次检查缓存中是否存在shop
            shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
            if (StrUtil.isNotBlank(shopJson)) {
                // 存在则直接返回
                return JSONUtil.toBean(shopJson, Shop.class);
            }

            // 4.3 缓存中不存在shop，根据id查询数据库
            shop = getById(id);
            // 假装耗时
            //Thread.sleep(200);

            // 5. 不存在，返回错误，将空值写入Redis
            if (null == shop) {
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",
                        RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 6. 存在，将shop写入Redis
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY +id, JSONUtil.toJsonStr(shop),
                    RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch(InterruptedException e){
            throw new RuntimeException(e);
        } finally {
            // 7. 释放锁
            unLock(lock);
        }

        return shop;

    }

    public boolean tryLock(String lock){

        // setNX锁(setIfAbsent)：只有key不存在时，设置成功
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lock, "1",
                RedisConstants.LOCK_MUTEX_TTL, TimeUnit.SECONDS);
        // 手动拆箱
        return BooleanUtil.isTrue(flag);
    }

    public void unLock(String lock){
        stringRedisTemplate.delete(lock);
    }



    /**
     * 只解决缓存穿透
     * @param id
     * @return
     */
    public Shop queryWithPassThrough(Long id){
        // 1. 从Redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        // 2. 判断缓存中是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3. 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        // 4. 判断命中的是否是空值
        if("".equals(shopJson)){
            return null;
        }

        // 4. 不存在，根据id查询数据库
        Shop shop = getById(id);

        // 5. 不存在，返回错误，将空值写入Redis
        if (null == shop) {
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",
                    RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 6. 存在，写入Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY +id, JSONUtil.toJsonStr(shop),
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }



    @Override
    //@Transactional Spring只能管理关系型数据库的事务，不支持NoSQL数据库的事务管理
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (null == id) {
            return Result.fail("店铺id不能为空！");
        }

        // 1. 更新数据库
        updateById(shop);
        // 2. 删除Redis缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);

        return Result.ok();
    }


}
